package com.example.group_20.service.Impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.group_20.entity.*;
import com.example.group_20.mapper.*;
import com.example.group_20.service.StudentsService;
import com.example.group_20.utils.FileUtils;
import com.example.group_20.utils.JwtUtils;
import com.example.group_20.utils.Result;
import com.example.group_20.utils.SLogUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.sql.Date;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;

/**
 * @author: 栋
 * @data: 2023/8/11
 * @descriptions:
 */
@Service
public class StudentsServiceImpl implements StudentsService {
    @Autowired
    private StudentsMapper studentsMapper;
    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private ChatMapper chatMapper;
    @Autowired
    private RateMapper rateMapper;
    @Autowired
    private FilesMapper filesMapper;
    @Autowired
    private SLogMapper sLogMapper;
    @Override
    public Result login(String s_id, String pwd) {
//        System.out.println("登录中");
//        System.out.println(s_id);
        Students students = studentsMapper.findByid(s_id);
//        System.out.println(students);
//        System.out.println(pwd);
        if(students!=null){
            if(pwd.equals(students.getS_password())) {
                String token = JwtUtils.generateToken(s_id);
                return Result.Ok().data("token", token);
            }
        }
        return Result.Error().msg("Account and password are incorrect.");
    }

    @Override
    public Result logout() {

        return Result.Ok().data("sucess","sucess");
    }

    @Override
    public Result updateInfor(Students students) {
        Students students1=studentsMapper.findByid(students.getS_id());
        students1.setS_email(students.getS_email());
        students1.setS_tel(students.getS_tel());
        int res = studentsMapper.updateInfor(students1);
        if(res!=0){
            return Result.Ok().msg("修改成功").data("message","success");
        }else {
            return Result.Error().msg("修改失败").data("message","error");
        }
    }

    @Override
    public Result updatePwd(Students students, String newpwd) {
        Students students1=studentsMapper.findByid(students.getS_id());
        if(students.getS_password().equals(students1.getS_password())){
            students1.setS_password(newpwd);
            int res=studentsMapper.updateInfor(students1);
            if(res!=0){
                return Result.Ok().msg("修改成功").data("message","success");
            }else {
                return Result.Error().msg("修改失败").data("message","error");
            }
        }else{
            return Result.Error().msg("原密码输入有误").data("message","error");
        }


    }

    @Override
    public Result getInfor(String token) {
        String s_id = JwtUtils.getClaimsByToken(token).getSubject();
        Students students = studentsMapper.findByid(s_id);
        return Result.Ok().data("students",students);
    }

    @Override
    public Result showInfor(String token) {
        String s_id = JwtUtils.getClaimsByToken(token).getSubject();
        Students students = studentsMapper.findByid(s_id);
        int group_id=students.getGroup_id();
        if(group_id!=0) {
            Group group = groupMapper.findByid(group_id);
            List<Students> list=studentsMapper.findByGroup(group_id);
            Teachers teachers=teacherMapper.findByid(group.getT_id());
            return Result.Ok()
                    .data("students",students)
                    .data("list",list)
                    .data("teacher",teachers)
                    .data("groups",null);
        }else{
            List<Group> groups = groupMapper.findAll();
            return Result.Ok()
                    .data("students",students)
                    .data("list",null)
                    .data("teacher",null)
                    .data("groups",groups);

        }

    }

    @Override
    public Result showGroupInfor(String s_id) {
        return null;
    }

    @Override
    public Result subFile(Map<String,Object> mp) {
        StringBuilder s_id=new StringBuilder("");
        StringBuilder path=new StringBuilder("");
        MultipartFile file=(MultipartFile) mp.get("file");
        int category=0;
        if(mp.containsKey("s_id")){
            s_id.append(mp.get("s_id"));
        }
        if(mp.containsKey("path")){
            path.append(mp.get("path"));
        }
        if(mp.containsKey("category")){
           category=Integer.valueOf((String) mp.get("category")).intValue();
        }
        Students students = studentsMapper.findByid(s_id.toString());
        int group_id=students.getGroup_id();
        List<FilesInfor> byGroupAndCategory = filesMapper.findByGroupAndCategory(group_id, category);
        if(!byGroupAndCategory.isEmpty()){
            return Result.Error().msg("该类型文件已经提交过").data("message","error");
        }
//        //保存文件
//        path.append("/file/");


        Category c=categoryMapper.findByid(category);
        String type=c.getValue();
        String p=FileUtils.saveFile(file,path.toString(),type,group_id);
        //将文件信息保存到数据库
        //获取id
        List<FilesInfor> filesInforList=filesMapper.findAll();
        StringBuilder lastId=new StringBuilder("");
        if(!filesInforList.isEmpty()){
            int size1 = filesInforList.size();

            FilesInfor filesInfor=filesInforList.get(size1-1);
            lastId.append(filesInfor.getFile_id());
        }
        String file_id=FileUtils.getId(lastId.toString());


        //获取后缀名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //获取文件名
        String file_name = FileUtils.SetName(group_id, type, suffix);
        //获取文件大小
        long size = file.getSize();
        //获取时间
        Date sub_date=Date.valueOf(LocalDate.now());
        Time sub_time=Time.valueOf(LocalTime.now());
        int status=0;
        FilesInfor f=new FilesInfor(file_id,p,category,file_name,suffix,size,sub_date,sub_time,group_id,null,null,null,null,null,status);
        filesMapper.insert(f);
        List<SLogInfor> all = sLogMapper.finAll();
        StringBuilder lastId1=new StringBuilder("");
        if(!all.isEmpty()){
            int size1 = all.size();

            SLogInfor sLogInfor=all.get(size1-1);
            lastId1.append(sLogInfor.getId());
        }
        String sLogId= SLogUtils.getId(lastId1.toString());
        SLogInfor sLogInfor=new SLogInfor(sLogId,f.getGroup_id(),f.getFile_id(),f.getName(),1,sub_date,sub_time);
        sLogMapper.insert(sLogInfor);

        return Result.Ok().msg("提交成功").data("message","success");
    }


    @Override
    public Result backFile(Map<String,Object>mp) {
        String fileId =(String) mp.get("file_id");
        FilesInfor file = filesMapper.findById(fileId);
        int status = file.getStatus();
        if(status==0||status==5){
            filesMapper.deleteById(fileId);
            List<SLogInfor> all = sLogMapper.finAll();
            StringBuilder lastId=new StringBuilder("");
            if(!all.isEmpty()){
                int size1 = all.size();

                SLogInfor sLogInfor=all.get(size1-1);
                lastId.append(sLogInfor.getId());
            }
            String sLogId= SLogUtils.getId(lastId.toString());
            Date del_date=Date.valueOf(LocalDate.now());
            Time del_time=Time.valueOf(LocalTime.now());
            SLogInfor sLogInfor=new SLogInfor(sLogId,file.getGroup_id(),file.getFile_id(),file.getName(),0,del_date,del_time);
            sLogMapper.insert(sLogInfor);
            return Result.Ok().msg("撤销成功").data("message","success");
        }

        return Result.Error().msg("只能撤销未批改或者不及格的文件").data("message","error");
    }

    @Override
    public Result showFiles(String token) {
        String s_id = JwtUtils.getClaimsByToken(token).getSubject();
        Students students = studentsMapper.findByid(s_id);
        int groupId = students.getGroup_id();
        List<FilesInfor> filesInforList = filesMapper.findByGroup(groupId);
        List<Rate> allRate = rateMapper.findAll();

        return Result.Ok().data("files",filesInforList).data("rate",allRate);

    }

    @Override
    public Result showSOptions(String token) {
        String s_id = JwtUtils.getClaimsByToken(token).getSubject();
        Students students = studentsMapper.findByid(s_id);
        int groupId = students.getGroup_id();
        List<SLogInfor> sLogInfors = sLogMapper.findByGroup(groupId);
        return Result.Ok().data("SLogInfor",sLogInfors);
    }

    @Override
    public Result sendMsg(Map<String,Object> mp) {
        StringBuilder s_id=new StringBuilder("");
        StringBuilder teacher_id=new StringBuilder("");
        StringBuilder msg=new StringBuilder("");
        if(mp.containsKey("s_id")){
            s_id.append(mp.get("s_id"));
        }
        if(mp.containsKey("teacher_id")){
            teacher_id.append(mp.get("teacher_id"));
        }
        if(mp.containsKey("msg")){
            msg.append(mp.get("msg"));
        }
        Date date=Date.valueOf(LocalDate.now());
        Time time=Time.valueOf(LocalTime.now());
        Students students = studentsMapper.findByid(s_id.toString());
        Teachers teachers = teacherMapper.findByid(teacher_id.toString());
        if(teachers==null){
            return Result.Error().msg("发送对象不存在，请检查老师工号").data("message","error");
        }
        Chat chat=new Chat(0,msg.toString(),s_id.toString(),students.getS_name(),teacher_id.toString(),teachers.getT_name(),null,date,time,null,null,0);
        chatMapper.insert(chat);
        return Result.Ok().data("message","success").msg("发送成功");
    }

    @Override
    public Result showSendMsg(String token) {
        String s_id = JwtUtils.getClaimsByToken(token).getSubject();
        List<Chat> bySentId = chatMapper.findBySentId(s_id);
        return Result.Ok().data("msg",bySentId);
    }

    @Override
    public Result showReciveMsg(String token) {

        String s_id = JwtUtils.getClaimsByToken(token).getSubject();
        List<Chat> byReciveId = chatMapper.findByReciveId(s_id);
        return Result.Ok().data("msg",byReciveId);
    }

    @Override
    public Result reply(Map<String, Object> mp) {
        int id=0;
        StringBuilder response=new StringBuilder("");
        if(mp.containsKey("id")){
            id=(Integer) mp.get("id");
        }
        if(mp.containsKey("content")){
            response.append(mp.get("content"));
        }
        Date date=Date.valueOf(LocalDate.now());
        Time time=Time.valueOf(LocalTime.now());
        Chat chat = chatMapper.findByid(id);
        chat.setResp_date(date);
        chat.setResp_time(time);
        chat.setResponse(response.toString());
        chat.setStatus(1);
        int res = chatMapper.updateChatInfor(chat);
        if(res==1){
            return Result.Ok().msg("回复成功").data("message","success");
        }else{
            return Result.Error().msg("回复失败").data("message","error");
        }
    }

    @Override
    public Result selectGroup(Map<String, Object> mp) {
        StringBuilder group_id=new StringBuilder("");
        StringBuilder s_id=new StringBuilder("");
        if(mp.containsKey("group_id")){
            group_id.append(mp.get("group_id"));
        }
        if(mp.containsKey("s_id")){
            s_id.append(mp.get("s_id"));
        }
        Group group = groupMapper.findByid(Integer.valueOf(group_id.toString()));
        Students students = studentsMapper.findByid(s_id.toString());
        students.setGroup_id(group.getGroup_id());
        if(group.getS1_id()==null){
            group.setS1_id(students.getS_id());
        }else if(group.getS2_id()==null){
            group.setS2_id(students.getS_id());
        }else if(group.getS3_id()==null){
            group.setS3_id(students.getS_id());
        }else if(group.getS4_id()==null){
            group.setS4_id(students.getS_id());
        }else if(group.getS5_id()==null){
            group.setS5_id(students.getS_id());
        }else if(group.getS6_id()==null){
            group.setS6_id(students.getS_id());
        }
        UpdateWrapper<Group> groupUpdateWrapper=new UpdateWrapper<>();
        groupUpdateWrapper.eq("group_id",group.getGroup_id());
        groupMapper.update(group,groupUpdateWrapper);
        studentsMapper.updateInfor(students);
        return Result.Ok().data("message","success").msg("选择成功");
    }


}
